<template>
    <view class="main_content" :style="{ backgroundImage: `url(${ossImg('others/2025Autumn/background/bg.png')})` }">
        <view class="mt-60rpx mb-16rpx">
            <canvas style="position: absolute;z-index: -10;left: 120rpx;bottom:-800rpx;" canvas-id="test-id"
                class="h-625rpx w-508rpx post-canvas"></canvas>
            <image :src="ossImg('others/2025Autumn/logo.png')" mode="widthFix" class="w-240rpx h-105rpx"></image>
        </view>
        <view class="changeFont">
            <image :src="ossImg('others/2025Autumn/change.png')" class="w-282rpx h-77rpx"
                style="position: relative;z-index: 1;"></image>
        </view>
        <view class="space"></view>
        <view ref="viewRef" class="decorateOutBox" id="decorateOutBox">
            <view class="decorateInnerBox" data-type="view">
                <view class="decoreteInfo">
                    <view class="leftRightSlider" data-type="view">
                        <image :src="ossImg('others/2025Autumn/leftRightSlider.png')" mode="widthFix"></image>
                    </view>
                    <!-- 自定义文字和参数 -->
                    <swiper :autoplay="false" @change="handleTextChange">
                        <swiper-item v-for="(item, index) in cookieConfig.adver" :key="index">
                            <ArcText class="" :text="item" :radius="265" :fontSize="40" :isUpperArc="false" />
                        </swiper-item>
                    </swiper>
                    <view class="biscuit" data-type="view">
                        <image :src="cookieConfig.image" mode="widthFix"></image>
                    </view>
                </view>
                <view class="decorateBox">
                    <view class="itemInfo">
                        <image :src="ossImg('others/2025Autumn/move.png')" mode="widthFix"></image>
                    </view>
                    <view v-for="(item, i) in cookieConfig.tool" class="itemBox"
                        :class="{ 'disabled': isItemDisabled(i) }" :key="`${i}-${forceUpdateKey.value}`">
                        <movable-area class="movable-area">
                            <movable-view :scale="true" @change="handleTouchMove($event, i)" class="movable-view"
                                :x="getCurrentX(i)" :y="getCurrentY(i)" direction="all" :disabled="isItemDisabled(i)"
                                :animation="false">
                                <ImageRotate :src="item" @change="rotateChange" />
                            </movable-view>
                        </movable-area>
                    </view>
                </view>
            </view>
        </view>
        <view @click="goToGenerateCookiePattern" class="btn-select" >
            <image mode="aspectFit" :src="ossImg('others/2025Autumn/btn/create.png')" class="w-[360rpx] h-[124rpx]"></image>
        </view>
        <view class="lineModel" :style="'background-image: url(' + cookieConfig.lineBackground + ');'"></view>
        <view class="cloudBg">
            <image :src="ossImg('others/2025Autumn/cloud.png')" mode="widthFix"></image>
        </view>
    </view>
</template>

<script setup>
import { onLoad,onShareAppMessage } from '@dcloudio/uni-app';
import { ref } from "vue";
import { ossImg } from "@/utils/utils";
import ArcText from './components/ArchText.vue';
import ImageRotate from "./components/ImageRotate.vue"
const enterTime = +new Date();
const emdlz = getApp().emdlz;
const cookieConfig = ref({});
const viewRef = ref(null)
const smallImgPosition = ref([])
const pxRatio = ref(1);
const textIndex = ref(0);
const forceUpdateKey = ref(0);
function rotateChange(){
  
}
function handleTextChange(e) {
    textIndex.value = e.detail.current;
    const cookieIndex = uni.getStorageSync('autumnSelectedCookiePatternIndex')
    if (cookieIndex != null) {
        const indexKeyMap = {
            0: "princess",
            1: "star",
            2: "magic",
            3: "lighthouse",
            4: "travel",
            5: "superman",
        }
        emdlz('track', 'event', `oreo_onpack_2025_interact_${indexKeyMap[cookieIndex]}`, 'click', `check_prop_${e.detail.current}`);
    }
}

// 计算元素的初始X坐标
function getElementX(index) {
    return (50 + 150 * (index % 3)) * pxRatio.value;
}

// 计算元素的初始Y坐标
function getElementY(index) {
    return (665 + Math.floor(index / 3) * 145) * pxRatio.value;
}
// 获取元素当前应该显示的X坐标
function getCurrentX(index) {
    // 总是返回实时计算的位置或初始位置
    return getElementX(index);
}

// 获取元素当前应该显示的Y坐标
function getCurrentY(index) {
    // 总是返回实时计算的位置或初始位置
    return getElementY(index);
}

// 判断元素是否应该被禁用
function isItemDisabled(index) {
    // 检查当前在装饰区域内的元素数量
    const inDecorateAreaCount = smallImgPosition.value.filter((pos, i) => {
        return pos && pos.y < 600 * pxRatio.value;
    }).length;

    // 检查当前元素是否已在装饰区域
    const isCurrentInDecorateArea = smallImgPosition.value[index] &&
        smallImgPosition.value[index].y < 600 * pxRatio.value;

    // 如果装饰区域未满，或者当前元素已在装饰区域，则不禁用
    if (inDecorateAreaCount < 3 || isCurrentInDecorateArea) {
        return false;
    }

    // 否则禁用
    return true;
}
function handleTouchMove(e, i) {
    const { x, y } = e.detail;
    const cookieIndex = uni.getStorageSync('autumnSelectedCookiePatternIndex')
    if (cookieIndex != null) {
        const indexKeyMap = {
            0: "princess",
            1: "star",
            2: "magic",
            3: "lighthouse",
            4: "travel",
            5: "superman",
        }
        emdlz('track', 'event', `oreo_onpack_2025_interact_${indexKeyMap[cookieIndex]}`, 'click', `check_prop_${i + 1}`);
    }
    // 只记录位置信息，不直接更新视图
    if (!smallImgPosition.value[i]) {
        smallImgPosition.value[i] = { x, y };
    } else {
        smallImgPosition.value[i].x = x;
        smallImgPosition.value[i].y = y;
    }

    // 检查元素是否被拖回工具区域
    if (y >= 600 * pxRatio.value) {
        smallImgPosition.value[i] = null;
        // 强制更新视图
        forceUpdateKey.value++;
    }
}

onLoad(() => {
    const index = uni.getStorageSync('autumnSelectedCookiePatternIndex')
    const config = uni.getStorageSync('autumnConfig');
    cookieConfig.value = config.biscuit[index];
    const systemInfo = uni.getSystemInfoSync();
    pxRatio.value = systemInfo.windowWidth / 750; // rpx转px比例

    // 初始化拖动状态
    smallImgPosition.value = [];
})

const resetDragged = () => {
    // 清空位置信息
    smallImgPosition.value = [];

    // 通过改变key来强制重新渲染所有movable-view
    forceUpdateKey.value++;

    // 如果上面还不够，再添加一个小延迟
    setTimeout(() => {
        forceUpdateKey.value++;
    }, 50);
}
onShareAppMessage((e) => {
	
	const shareObj = {
		title: "进来！你的玩心梦想竟然是…", // 默认是小程序的名称(可以写slogan等)
		path: "/campaign/pages/2025Autumn/index", // 默认是当前页面，必须是以‘/’开头的完整路径
		imageUrl: ossImg("others/2025Autumn/shareBiscuit.jpg"), //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
		success: (res) => {
			// 转发成功之后的回调
			if (res.errMsg == "shareAppMessage:ok") {
			}
		},
		fail: (err) => {
			// 转发失败之后的回调
			console.log("转发失败之后的回调", err);
			if (res.errMsg == "shareAppMessage:fail cancel") {
				// 用户取消转发
				console.log("用户取消转发");
			} else if (res.errMsg == "shareAppMessage:fail") {
				// 转发失败，其中 detail message 为详细失败信息
				console.log("转发失败，其中detail message 为详细失败信息");
			}
		},
		complete: () => {
			console.log("转发结束之后的回调（转发成不成功都会执行）");
		},
	};
	console.log(shareObj);
	return shareObj;
});
function draw() {
    // 首先获取View的尺寸和位置信息
    wx.createSelectorQuery().select('#decorateOutBox').boundingClientRect(async function (rect) {
        // 然后将View的内容绘制到Canvas上
        const ctx = wx.createCanvasContext('test-id', viewRef.value);
        const systemInfo = uni.getSystemInfoSync();
        const pxRatio = systemInfo.windowWidth / 750; // rpx转px比例
        const width = 508 * pxRatio
        const height = 625 * pxRatio
        const radius = 120
        // 1. 绘制渐变背景（60%到100%区域）
        // const gradient = ctx.createLinearGradient(0, 0, 0, width);
        // gradient.addColorStop(0.6, '#1645c6');
        // gradient.addColorStop(1, '#5761e9');

        // ctx.setFillStyle("#fff");
        // ctx.fillRect(0, 0, width, height);


        // 2. 添加图片（391rpx）
        try {
            const imgSize = 391 * pxRatio;
            const res = await uni.getImageInfo({
                src: cookieConfig.value.image // 替换为实际图片URL
            });
            ctx.drawImage(res.path, (width - imgSize) / 2, 165 * pxRatio, imgSize, imgSize);
            ctx.font = 'fzround';
            ctx.setFontSize(42 * pxRatio);
            ctx.setFillStyle('#630eed');

            // 获取文字内容和长度
            const text = cookieConfig.value.adver[textIndex.value];
            const textLength = text.length;

            if (textLength === 0) return;

            // 计算圆弧中心位置（Canvas中心）
            const centerX = width / 2;
            const centerY = height / 2 + 60 * pxRatio;;

            // 计算总角度（弧度），根据文字长度动态调整
            const totalAngle = Math.min(Math.PI * 1.5, textLength * 0.2);

            // 计算每个字符的角度间隔
            const angleStep = totalAngle / (textLength - 1);

            // 计算起始角度（左侧开始）
            const startAngle = -totalAngle / 2;

            // 逐个绘制文字
            for (let i = 0; i < textLength; i++) {
                // 计算当前字符的角度
                const angle = startAngle + i * angleStep;
                console.log(angle, 'angle');

                // 计算文字位置
                const x = centerX + radius * Math.sin(angle);
                const y = centerY - radius * Math.cos(angle);

                // 保存当前上下文状态
                ctx.save();

                // 移动到文字位置
                ctx.translate(x, y);

                // 旋转文字，使其沿圆弧方向排列
                ctx.rotate(angle);

                // 绘制文字（文字居中对齐）
                ctx.fillText(text[i], 0, 0);

                // 恢复上下文状态
                ctx.restore();
            }
            // 绘制小图
            for (let index = 0; index < smallImgPosition.value.length; index++) {
                const element = smallImgPosition.value[index];
                if (element) {
                    let x = element.x; // 图片起始横坐标
                    let y = element.y; // 图片起始纵坐标
                    let width = 135 * pxRatio; // 图片宽度（根据实际需要调整）
                    let height = width; // 图片高度（根据实际需要调整）
                    const res = await uni.getImageInfo({
                        // src: cookieConfig.value.tool[index] // 替换为实际图片URL
                        src: cookieConfig.value.tool[index] // 替换为实际图片URL
                    });
                    ctx.drawImage(res.path, x, y, width, height);
                }
            }
        } catch (err) {
            console.error('图片加载失败:', err);
        }

        ctx.draw();
        wx.canvasToTempFilePath({
            x: 0, // View的x坐标，相对于画布的左上角
            y: 0, // View的y坐标，相对于画布的左上角
            width, // View的宽度
            height, // View的高度
            destWidth: width, // 输出图片的宽度
            destHeight: height, // 输出图片的高度
            canvasId: 'test-id', // 要绘制的Canvas的ID
            success: function (res) {
                console.log('图片已保存到本地路径', res.tempFilePath);
                uni.setStorageSync("temp_img", res.tempFilePath)
                setTimeout(() => {
                    uni.navigateTo({
                        url: "/campaign/pages/2025Autumn/generateCookiePattern"
                    })
                    if (enterTime) {
                        emdlz('track', 'event', 'oreo_onpack_2025_interact_1', 'view', 'interact_1', (+new Date() - enterTime) / 1000);
                    }
                }, 500)
                // const ctx = wx.createCanvasContext('test-id', viewRef.value);
                // ctx.drawImage(res.tempFilePath, 0, 0, 300, 200);
                // ctx.draw();
                // 可以在这里将图片保存到相册或者做其他处理
                // wx.saveImageToPhotosAlbum({
                //     filePath: res.tempFilePath,
                //     success(result) {
                //         console.log('保存成功', result)
                //     }
                // })
            },
            fail: function (err) {
                console.error('截图失败', err);
            }
        }, viewRef.value);
    }).exec();
}
const goToGenerateCookiePattern = async (e) => {
		// draw()
		const user = getApp().globalData?.user
		const data = {
			"bg": uni.getStorageSync('autumnSelectedCookiePatternIndex') + 1,
			"text": textIndex.value + 1,
			"memberId": user?.memberScore?.memberId || '',
			"token":uni.getStorageSync("TOKEN"),
			stickers: []
		}
		const systemInfo = uni.getSystemInfoSync();
		const pxRatio = systemInfo.windowWidth / 750; // rpx转px比例
		// console.log(item.x/(pxRatio * 390)*390)
		smallImgPosition.value.forEach((item,i) => {
			if (item) {
				data.stickers.push({
					id: '00' + (i + 1),
					x: item.x/(pxRatio * 390)*390,
					y: item.y/(pxRatio * 625)*625,
					width: item.width || 135,
					height: item.height || 135,
					rotate: 0
				})
			}
		})
		uni.showLoading({ title: '生成图片中' });
		uni.request({
		  url: `https://gifservice.mykeying.com/generate`,
		  method: "post",
		  data: data,
		  success(res){
			  console.log(res.data)
			  uni.setStorageSync("temp_img", res.data.data.url)
			  setTimeout(() => {
			  	uni.navigateTo({
			  		url: "/campaign/pages/2025Autumn/generateCookiePattern"
			  	})
			  }, 500)
		  },
		  complete(){
			  uni.hideLoading();
		  }
		});
	}

</script>
<style lang="less" scoped>
@import "@/static/css/theme.less";
@import "@/static/css/autumn/main.less";

.movable-area {
    //  可移动的范围
    height: 1025rpx;
    width: 528rpx;
    top: 220rpx;
    left: 111rpx;
    position: fixed;
    pointer-events: none; //鼠标事件可以渗透
    z-index: 1000;
}

.movable-view {
    width: 135rpx; // 按钮大小
    height: 135rpx;
    pointer-events: auto; //恢复鼠标事件
}

.movable-view[disabled] {
    opacity: 0.5; // 禁用时降低透明度
}

.itemBox.disabled {
    opacity: 0.5;
}

.itemBox.disabled .movable-view {
    pointer-events: none;
}


.main_content {
    view {
        margin: 0 auto;
        text-align: center;
    }

    .changeFont {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        top: 180rpx;
        z-index: 20;
    }

    .space {
        height: 50rpx;
        display: block;
    }

    font-family: autumn;
    width: 100%;
    height: 100vh;
    box-sizing: border-box;
    padding-top: 30px;
    background-size: cover;
    position: fixed;
    top:0;
    left:0;
    right:0;
    bottom:0;
    z-index:1000;
}

.swiper-container {
    width: 100%;
    height: 200px;
    /* 根据需要调整 */
}

.swiper {
    height: 100%;
}

.swiper-item {
    display: flex;
    justify-content: center;
    align-items: center;

    &.swiper-item-active {
        overflow: inherit;
        z-index: 99;
    }
}

.slide-image {
    // width: 0;
    flex: 0 0 200rpx;
    height: 200rpx;
    /* 默认大小 */
    transition: transform 0.3s ease;
    /* 平滑过渡效果 */
}

.slide-image.active {
    flex: 0 0 400rpx;
    height: 400rpx;
    /* 当前图片放大 */
    // transform: scale(1.2);
    /* 可以调整放大比例 */
}

.btn-select {
    width:100%;
    text-align: center;
    color: #fff;
    position: absolute;
    z-index: 11;
	top:1180rpx;
}
/* 分享页面外框 */
.outBox {
    background: linear-gradient(to bottom, #b892fe, #9380f1, #033dbf) 40% 100%;
    padding: 8rpx;
    border-radius: 50rpx;
    box-shadow: 0 5rpx 20rpx rgba(0, 0, 0, 0.3);
    width: 528rpx;
    height: 1025rpx;
    transform: translateY(-50rpx);
}

.innerBox {
    background: linear-gradient(to bottom, #fff, #ffe1ee) 40% 100%;
    padding: 10rpx;
    border-radius: 45rpx 45rpx 0 0;
    box-sizing: border-box;
    height: 630rpx;
}

/* 装饰页面背景 */
.decorateOutBox {
    width: 528rpx;
    height: 1010rpx;
    background: linear-gradient(to bottom, #b892fe, #9380f1, #495ed7, #033dbf) 60% 100%;
    padding:8rpx;
    border-radius: 50rpx;
    box-shadow: 0 5rpx 20rpx rgba(0, 0, 0, 0.5);
    margin-top: 50rpx;
    display: block;
    position: relative;
    z-index: 10;
}

.decorateInnerBox {
    width: 100%;
    height: 100%;
    background: #fff;
    padding: 0;
    border-radius: 45rpx;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    flex-wrap: wrap;
}

.decoreteInfo {
    width: 100%;
    height:590rpx;
    position: relative;
}

.decoreteInfo .leftRightSlider {
    padding: 40rpx 0 20rpx;
}

.decoreteInfo .leftRightSlider image {
    width: 188rpx;
    height: 32rpx;
}

.decoreteInfo .biscuit {
    clear: both;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 170rpx;
}

.decoreteInfo .biscuit image {
    width: 345rpx;
    height: 348rpx;
}
.decorateBox {
    width: 100%;
    height: 395rpx;
    background: linear-gradient(to bottom, #1645c6, #5761e9) 60% 100%;
    border-radius: 0 0 40rpx 40rpx;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    align-content: flex-start;
    flex-wrap: wrap;
    padding: 15rpx 35rpx;
}

.decorateBox .itemInfo {
    width: 100%;
    text-align: center;
    padding: 0 0 10rpx;
}

.decorateBox .itemInfo image {
    width: 417rpx;
    height: 22rpx;
}

.decorateBox .decorateList {
    width: 100%;
    height: auto;
    overflow: hidden;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    align-content: flex-start;
    flex-wrap: wrap;
}

.decorateBox .itemBox {
    width: 135rpx;
    height: 135rpx;
    overflow: hidden;
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 8rpx;
    position: relative;
    overflow: hidden;
    padding: 0;
}

.decorateBox .itemBox image {
    width: 100%;
    height: 100%;
}

.decorateBox .itemBox:nth-child(2) {
    background: linear-gradient(to right bottom, #456be9, #8b7ff4) 40% 100%;
}

.decorateBox .itemBox:nth-child(3) {
    background: linear-gradient(to right bottom, #4c6dea, #8b7ef4, #274ecb) 40% 100%;
}

.decorateBox .itemBox:nth-child(4) {
    background: linear-gradient(to right bottom, #7378f0, #496cea, #8b7ef4) 40% 100%;
}

.decorateBox .itemBox:nth-child(5) {
    background: linear-gradient(to right bottom, #4c6dea, #8b7ef4, #456be9) 40% 100%;
}

.decorateBox .itemBox:nth-child(6) {
    background: linear-gradient(to right bottom, #7378f0, #456be9, #8b7ef4) 20% 100%;
}

.decorateBox .itemBox:nth-child(7) {
    background: linear-gradient(to right bottom, #4c6dea, #8b7ef4, #274ecb) 20% 100%;
}

.post-canvas {
    position: fixed;
}
</style>
